package cj.web.admin.controllers;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.Path;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.var.Model;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import cj.utils.Constants;
import cj.utils.DateUtils;
import cj.web.admin.dao.VoteDAO;
import cj.web.admin.dao.VoteItemDAO;
import cj.web.admin.dao.VoteSubjectDAO;
import cj.web.admin.domain.Vote;
import cj.web.admin.domain.VoteItem;
import cj.web.admin.domain.VoteSubject;
import cj.web.constants.MemuEnum;
import cj.web.constants.isLoginEnum;
import cj.web.constants.isMutilEnum;
import cj.web.login.controllers.BaseController;

@Path("/vote")
public class VoteController extends BaseController{

	private static Logger logger = Logger.getLogger(VoteController.class.getName());
	
	@Autowired
	private VoteDAO voteDao;
	
	@Autowired
	private VoteItemDAO voteItemDao;
	
	@Autowired
	private VoteSubjectDAO voteSubjectDao;
	
	@Get("show")
	public String show(Model model, HttpServletRequest request) {
	
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("isLoginEnum",EnumSet.allOf(isLoginEnum.class));
		return "/views/vote/voteList.vm";
	}

	@Post("getList")
	public String queryList(Vote vote) {
	
		List<Vote> arr = voteDao.query(vote);
		
		for(Vote obj:arr)
		{
			obj.setVoteStart(DateUtils.getMinusTime(obj.getVoteStart(), DateUtils.DATE_FULL_STR, 0));
			obj.setVoteEnd(DateUtils.getMinusTime(obj.getVoteEnd(), DateUtils.DATE_FULL_STR, 0));
		}
		
		JSONObject jo = new JSONObject();
		
		int size = voteDao.querysize(vote);
		
		jo.put("data", arr);
		jo.put("draw", vote.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("createPage")
	public String createPage(Model model){
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("isLoginEnum",EnumSet.allOf(isLoginEnum.class));
		return "/views/vote/voteDetail.vm";
	}
	
	@Post("create")
	public String create(Model model,Vote vote,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			vote.setCreateUser(returnSessionObj(request).getAccount());
			vote.setUpdateUser(returnSessionObj(request).getAccount());
			voteDao.create(vote);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("edit")
	public String edit(Model model,@Param("id") int id){
		
		Vote vote =voteDao.queryById(id);
		
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("isLoginEnum",EnumSet.allOf(isLoginEnum.class));
        model.add("obj",vote);
		return "/views/vote/voteEdit.vm";
	}
	
	@Post("update")
	public String update(Model model,Vote vote,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			vote.setUpdateUser(returnSessionObj(request).getAccount());
			voteDao.update(vote);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteById")
	public String deleteById(Model model,@Param("id") int id){
		voteDao.deleteById(id);
		return "r:show";
	}
	
	//--------VoteSubject--------
	@Get("showSj")
	public String showSubject(Model model,@Param("id") int id, HttpServletRequest request) {
		Vote vote =voteDao.queryById(id);
		//MemuEnum
		model.add("voteId",id);
		model.add("vote",vote);
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("isMutilEnum",EnumSet.allOf(isMutilEnum.class));
		return "/views/vote/voteSubjectList.vm";
	}

	@Post("getSjList")
	public String querySubjectList(VoteSubject voteSubject) {
	
		List<Map> arr = voteSubjectDao.query(voteSubject);
		
		for(Map subject : arr){
			int subjectId = Integer.parseInt(subject.get("id").toString());
			List<Map> itms = voteItemDao.queryBySubjectId(subjectId);
			int total = 0;
			if(itms != null && itms.size() > 0){
				for(Map itm : itms){
					int count = Integer.parseInt(itm.get("count").toString());
					total += count;
				}
			}
			
			subject.put("total", total);
		}
		
		JSONObject jo = new JSONObject();
		
		int size = voteSubjectDao.querysize(voteSubject);
		
		jo.put("data", arr);
		jo.put("draw", voteSubject.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("createSjPage")
	public String createSubjectPage(Model model,@Param("voteId") int voteId){
		//MemuEnum
		model.add("voteId",voteId);
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("isMutilEnum",EnumSet.allOf(isMutilEnum.class));
		return "/views/vote/voteSubjectDetail.vm";
	}
	
	@Post("createSj")
	public String createSubject(Model model, @Param("voteId")int voteId, @Param("isMutil")int isMutil, 
			@Param("subject")String subject, @Param("items")String items, @Param("count")int count, HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			String user = returnSessionObj(request).getAccount();
			int subjectId = voteSubjectDao.create(voteId, isMutil, subject, user,count);
			
			JSONArray jaItms = JSONArray.fromObject(items);
			for(int i = 0; i < jaItms.size(); i++){
				String item = jaItms.getString(i);
				voteItemDao.create(voteId, subjectId, item, user, i);
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("editSj")
	public String editSubject(Model model,@Param("id") int id){
		
		VoteSubject voteSubject =voteSubjectDao.queryById(id);
		int subjectId = voteSubject.getId().intValue();
		List<Map> items = voteItemDao.queryBySubjectId(subjectId);
		
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("isMutilEnum",EnumSet.allOf(isMutilEnum.class));
        model.add("obj",voteSubject);
        model.add("Items",items);
		return "/views/vote/voteSubjectEdit.vm";
	}
	
	@Post("updateSj")
	public String updateSubject(Model model, @Param("voteId")int voteId, @Param("subjectId")int subjectId, @Param("isMutil")int isMutil, 
			@Param("subject")String subject, @Param("items")String items, @Param("delItms")String delete, @Param("count")int count, 
			HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		String user = returnSessionObj(request).getAccount();
		
		try {
			voteSubjectDao.update(subjectId, voteId, isMutil, subject, user, count);
			JSONArray jaItms = JSONArray.fromObject(items);
			if( null != jaItms && jaItms.size() > 0 ){
				for(int i = 0; i < jaItms.size(); i++){
					JSONObject joItm = jaItms.getJSONObject(i);
					int itemId = joItm.getInt("itemId");
					String item = joItm.getString("item");
					if(itemId > -1){
						voteItemDao.update(itemId, voteId, subjectId, item, user, i);
					}
					else{
						voteItemDao.create(voteId, subjectId, item, user, i);
					}
				}
			}
			
			JSONArray jaDelItms = JSONArray.fromObject(delete);
			if( null != jaDelItms && jaDelItms.size() > 0 ){
				for(int i = 0; i < jaDelItms.size(); i++){
					int itemId = jaDelItms.getInt(i);
					voteItemDao.deleteById(itemId);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteSjById")
	public String deleteSubjectById(Model model,@Param("id") int id){
		
		VoteSubject voteSubject =voteSubjectDao.queryById(id);
		
		if(voteSubject!=null)
		{
			voteSubjectDao.deleteById(id);
		}
		
		return "r:showSj?id="+voteSubject.getVoteId();
	}
	
	@Get("stickSj")//置顶Subject
    public String stickSubject(@Param("id") int id) {
		VoteSubject obj = voteSubjectDao.queryById(id);
		
		if(obj!=null){
			voteSubjectDao.updateByStickTime(id);
		}
		return "r:showSj?id="+obj.getVoteId();
	}
	
	@Get("channelStickSj")//取消置顶Subject
    public String channelStickSubject(@Param("id") int id) {
		VoteSubject obj = voteSubjectDao.queryById(id);
		
		if(obj!=null){
			voteSubjectDao.updateByStickTimeIsNull(id);
		}
		return "r:showSj?id="+obj.getVoteId();
	}
	
	//--------VoteItem--------
	@Get("showItem")
	public String showItem(Model model,@Param("id") int id,@Param("voteId") int voteId, HttpServletRequest request) {
	
		VoteSubject voteSubject =voteSubjectDao.queryById(id);
		//MemuEnum
		model.add("subjectId",id);
		model.add("voteId",voteId);
		model.add("voteSubject",voteSubject);
        model.add("MemuEnum",MemuEnum.lkgtpgl);
		return "/views/vote/voteItemList.vm";
	}

	@Post("getItemList")
	public String queryItemList(VoteItem voteItem) {
	
		List<Map> items = voteItemDao.query(voteItem);
		
		int total = 0;
		if(null != items && items.size() > 0){
			for(Map item : items){
				int count = Integer.parseInt(item.get("count").toString());
				total += count;
			}
			
			if(total == 0){
				for(Map item : items){
					item.put("percent", "0%");
				}
			}
			else{
				for(int i = 0; i < items.size(); i++){
					int count = Integer.parseInt(items.get(i).get("count").toString());
					if( count == 0 ){
						items.get(i).put("percent", "0%");
					}
					else{
						String percent = accuracy(count, total, 2);
						items.get(i).put("percent", percent + "%");
					}
					
				}
			}
		}
		
		JSONObject jo = new JSONObject();
		
		int size = voteItemDao.querysize(voteItem);
		
		jo.put("data", items);
		jo.put("draw", voteItem.getDraw());
		jo.put("recordsTotal", size);
		jo.put("recordsFiltered", size);
		return "@" + jo.toString();
	}
	
	@Get("createItemPage")
	public String createItemPage(Model model,@Param("subjectId") int subjectId,@Param("voteId") int voteId){
		//MemuEnum
		model.add("voteId",voteId);
		model.add("subjectId",subjectId);
        model.add("MemuEnum",MemuEnum.lkgtpgl);
		return "/views/vote/voteItemDetail.vm";
	}
	
	@Post("createItem")
	public String createItem(Model model,VoteItem voteItem,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			voteItem.setCreateUser(returnSessionObj(request).getAccount());
			voteItem.setUpdateUser(returnSessionObj(request).getAccount());
//			voteItemDao.create(voteItem);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("editItem")
	public String editItem(Model model,@Param("id") int id){
		
		VoteItem voteItem =voteItemDao.queryById(id);
		
		//MemuEnum
        model.add("MemuEnum",MemuEnum.lkgtpgl);
        model.add("obj",voteItem);
		return "/views/vote/voteItemEdit.vm";
	}
	
	@Post("updateItem")
	public String updateItem(Model model,VoteItem voteItem,HttpServletRequest request){
		JSONObject jo = new JSONObject();
		jo.put("returnFlag", Constants.returnObj.returnFlag_true);
		
		try {
			voteItem.setUpdateUser(returnSessionObj(request).getAccount());
//			voteItemDao.update(voteItem);
		} catch (Exception e) {
			// TODO: handle exception
			jo.put("returnFlag", Constants.returnObj.returnFlag_flase);
		}
		
		return "@"+jo.toString();
	}
	
	@Get("deleteItemById")
	public String deleteItemById(Model model,@Param("id") int id,@Param("voteId") int voteId){
		
		VoteItem voteItem =voteItemDao.queryById(id);
		if(voteItem!=null)
		{
			voteItemDao.deleteById(id);
		}
		
		return "r:showItem?id="+voteItem.getSubjectId()+"&voteId="+voteId;
	}
	
	@Get("stickItem")//置顶Subject
    public String stickItem(@Param("id") int id) {
		VoteItem obj = voteItemDao.queryById(id);
		
		if(obj!=null){
			voteItemDao.updateByStickTime(id);
		}
		return "r:showItem?id="+obj.getSubjectId()+"&voteId="+obj.getVoteId();
	}
	
	@Get("channelStickItem")//取消置顶Subject
    public String channelStickItem(@Param("id") int id) {
		VoteItem obj = voteItemDao.queryById(id);
		
		if(obj!=null){
			voteItemDao.updateByStickTimeIsNull(id);
		}
		return "r:showItem?id="+obj.getSubjectId()+"&voteId="+obj.getVoteId();
	}
	
	private String accuracy(double num, double total, int scale) {
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		// 可以设置精确几位小数
		df.setMaximumFractionDigits(scale);
		// 模式 例如四舍五入
		df.setRoundingMode(RoundingMode.HALF_UP);
		double accuracy_num = num / total * 100;
		return df.format(accuracy_num);
	}
}
